<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | 使用第三方模板引擎 Smarty，在响应前处理模板数据渲染
// +----------------------------------------------------------------------
namespace Inphp\Core\Middlewares;

use Inphp\Core\Config;
use Inphp\Core\Context;
use Inphp\Core\Helper\SmartyPlugin;
use Inphp\Core\Services\Http\Session;

class SmartyView implements IMiddleware
{
    /**
     * 初始化Smarty
     * @return \Smarty|null
     */
    public static function init(): ?\Smarty
    {
        if (!class_exists("\Smarty")) {
            return null;
        }
        //获取配置
        $config = Config::get("private.smarty");
        //客户端数据
        $client = Context::getClient();
        //新建模板对象
        $smarty = new \Smarty();
        $smarty->setLeftDelimiter($config["leftDelimiter"] ?? "{");
        $smarty->setRightDelimiter($config["rightDelimiter"] ?? "}");
        $smarty->setCacheLifetime($config["cacheLifetime"]);
        $smarty->setCaching($config["caching"]);
        $smarty->setCacheDir($config["cacheDir"]);
        $smarty->setCompileDir($config["compileDir"]);
        //一些基础配置
        $smarty->assign("app", Config::get("public.app", []));
        $smarty->assign("env", Config::get("env"));
        $domain = Config::get("domain");
        $domain["main"] = $domain["main"] ?? $client->host;
        $domain["main"] = stripos($domain["main"], "http") === 0 ? $domain["main"] : (($client->https ? "https://" : "http://").$domain["main"]);
        $smarty->assign("domain", $domain);
        $smarty->assign("get", $client->get);
        $smarty->assign("post", $client->post);
        $smarty->assign("cookies", $client->getCookieValues());
        $smarty->assign("session", Session::get());
        //获取控制器的临时数据
        $dataList = getViewAssignData();
        $dataList = is_array($dataList) ? $dataList : [];
        if (!empty($dataList)) {
            $smarty->assign($dataList);
        }
        //自定义控件
        foreach (["function", "modifier", "block"] as $type) {
            if(!empty(SmartyPlugin::$list[$type])){
                foreach (SmartyPlugin::$list[$type] as $pluginName => $plugin){
                    $smarty->registerPlugin($type, $pluginName, $plugin);
                }
            }
        }
        return $smarty;
    }

    /**
     * 处理...
     * @param ...$args
     */
    public static function process(...$args)
    {
        if (!($smarty = self::init())) {
            return;
        }
        //仅接收一个参数
        list($response) = $args;
        $routerStatus = $response->getRouterStatus();
        $smarty->assign("method", $routerStatus->controller[1] ?? null);
        //如果控制器有数据返回
        if (!empty($response->data)) {
            $smarty->assign("data", $response->data);
        }
        if ($routerStatus && $routerStatus->responseContentType === "text/html" && !empty($routerStatus->viewDir) && !empty($routerStatus->view) && is_file($routerStatus->viewDir."/".$routerStatus->view) && $routerStatus->status == 200) {

            //设置模板
            $smarty->setTemplateDir($routerStatus->viewDir);
            try {
                $response->withHtml($smarty->fetch($routerStatus->view));
            } catch (\Exception $exception) {
                $response->error(500, $exception->getMessage());
            }
        }
    }
}